package com.mt.util;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.xml.ws.http.HTTPException;
import java.io.IOException;
import java.util.Random;

/**
 * @author Wang
 * @Description 腾讯云短信工具类
 * @date 2021/2/8-13:04
 */
@Component
@Slf4j
public class MessageUtil {
    private static final Integer APPID          = 1400263577;
    private static final String  APPKEY         = "371b7d77c242220f420400999bb7f1eb";
    private static final Integer TEMPLATE_ID    = 430146;
    private static final String  SMS_SIGN       = "文件存储";
    private static final String  EFFECTIVE_TIME = "5";
    private static final String  NATION_CODE    = "86";
    private static SmsSingleSender  smsSingleSender= null;
    static{
        smsSingleSender =  new SmsSingleSender(APPID, APPKEY);
    }

    /**
     * 根据用户输入的手机号码发送6位随机数字验证码
     * @param phoneNumbers 用户的手机号码
     * @return 若发送成功则返回验证码，若失败则返回错误信息
     */
    public  Boolean sendMessage(String phoneNumbers,String code) {
        try {
            String[] params = {code, EFFECTIVE_TIME};
            SmsSingleSenderResult sendResult = smsSingleSender.sendWithParam(NATION_CODE, phoneNumbers, TEMPLATE_ID, params, SMS_SIGN, "", "");
            //返回0表示发送成功
            if (sendResult.result == 0) {
                return true;
            }
        } catch (HTTPException e) {
            log.error(e.toString());
            return false;
        }catch (com.github.qcloudsms.httpclient.HTTPException | IOException e) {
            log.error(e.toString());
        }
        return false;
    }
    /**
     * 生成6位随机验证码
     */
    public   String randomCode() {
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        int[] c = new int[6];
        for (int i = 0; i < 6; i++) {
            c[i] = r.nextInt(9) + 1;
            sb.append(c[i]);
        }
        return sb.toString();
    }
}

